#!/bin/sh

if [ $# -ne 2 ]
then
  echo "Usage: $0 CHAMPION CHALLENGER"
  exit 1
fi

CHAMPION=$1
CHALLENGER=$2
CHAMP=$(echo $CHAMPION | perl -ne '@n=split; print $n[-1]')
CHALL=$(echo $CHALLENGER | perl -ne '@n=split; print $n[-1]')

rm -f test*
printf "* //KerkerkruipScripts// fightchallenger\n$CHALLENGER" > fightchallenger
printf "* //KerkerkruipScripts// fightchampion\n$CHAMPION" > fightchampion
for DATAFILE in fightchallenger fightchampion
do
  cp $DATAFILE ${DATAFILE}.glkdata
done

TIMESTAMP=$(date "+%Y%m%d_%H%M")
if ! ./check-build.sh
then
  echo "No build."
  exit 2
fi
COMMIT=$(cat COMMIT)
TEST_ID="${TIMESTAMP}_${COMMIT}_${CHAMP}_${CHALL}"
FIGHT_COUNT=100

[ -f tmp.log ] && rm tmp.log
echo "$TEST_ID: Running $FIGHT_COUNT fights..."
for i in $(seq $FIGHT_COUNT)
do
  COLS=$(tput cols)
  TRANSCRIPT=$(printf "transcripts/${TEST_ID}_%03d.transcript" $i)
  ../i7/dumb-git -w $COLS Kerkerkruip.gblorb >$TRANSCRIPT
  WINNER=$(tail -n1 $TRANSCRIPT)
  if [ "$WINNER" = "ERROR" ]
  then
    echo "Fight fail! $(tail -n2 $TRANSCRIPT | head -n1) - Details in $TRANSCRIPT"
    exit 1
  fi
  [ -d transcripts ] || mkdir transcripts
  echo "$TRANSCRIPT winner: $WINNER" >> tmp.log

  CHALLENGER_WINS=$(egrep -c ": $CHALLENGER\$" tmp.log)
  CHAMPION_WINS=$(egrep -c ": $CHAMPION\$" tmp.log)
  tput rmam # disable line wrap
  PROGRESS="Fight $i winner: $WINNER ($CHAMPION: $CHAMPION_WINS, $CHALLENGER: $CHALLENGER_WINS)"
  printf "\r%-${COLS}s" "$PROGRESS" # print line padded to the right with blanks
  tput smam # enable line wrap
done

echo
echo "Fight test $TEST_ID summary: in $FIGHT_COUNT fights, $CHAMPION won $CHAMPION_WINS times, $CHALLENGER won $CHALLENGER_WINS times" >> tmp.log

tail -n1 tmp.log
cat tmp.log >> fighttest.log
rm tmp.log fightchallenger* fightchampion*


